package com.bxd.baodan.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.AlbumAddActivity;
import com.bxd.baodan.activity.InsuranceActivity;
import com.bxd.baodan.activity.ManualAdd1Activity;
import com.bxd.baodan.activity.MsgActivity;
import com.bxd.baodan.activity.TakePicturesAddActivity;
import com.bxd.baodan.activity.WebViewPager;
import com.bxd.baodan.adapter.BaoDanAdapter;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.BannerBean;
import com.bxd.baodan.item.InsuranceItemBean;
import com.bxd.baodan.listener.ScrollViewListener;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.Utils;
import com.bxd.baodan.util.VersionUtil;
import com.bxd.baodan.widget.BaoDanDialog;
import com.bxd.baodan.widget.MenuBar;
import com.bxd.baodan.widget.MyListView;
import com.bxd.baodan.widget.MyScrollView;
import com.bxd.baodan.widget.NetworkImageHolderView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;


public class MainBDFragment extends BaseFragment implements View.OnClickListener, OnItemClickListener {

    private Button mBtnAnli;
    private ImageView ring_msg;
    private LinearLayout mLlBeishu;
    private MyListView mLvBaodan;
    private MyScrollView myScrollView;
    private View lv_ly;
    private BaoDanAdapter mAdapter;

    private Boolean isLogin;
    private List<InsuranceItemBean.ListBean> mData;
    private List<BannerBean.BannerBean_> bannerList = new ArrayList<>();

    private boolean isLoad = true;
    private ImageView addBaoDan;
    private ConvenientBanner homeBanner;
    private FrameLayout title_bar;

private View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_baodan_manager, container, false);
        }
        ViewGroup viewGroup = (ViewGroup) view.getParent();
        if (viewGroup != null) {
            viewGroup.removeAllViewsInLayout();
        }
        initView();
        return view;
    }
    private void initView() {
        title_bar = view.findViewById(R.id.top_bar);
        title_bar.getBackground().setAlpha(0);
        title_bar.setPadding(title_bar.getPaddingLeft(), title_bar.getPaddingTop() + getStatusBarHeight(),
                title_bar.getPaddingRight(), title_bar.getPaddingBottom());
        myScrollView = view.findViewById(R.id.scrollView);
        homeBanner =  view.findViewById(R.id.home_banner);

        // FIXME: 17/7/14 解决listView跳动问题,将焦点设置到顶部view就行了

        myScrollView.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
                float fraction ;
                int maxHight = 5* title_bar.getHeight();
                if (y < 0) {
                    fraction = 0;
                } else  if ( y < maxHight) {
                     fraction = y * 1f / maxHight;
                } else {
                    fraction = 1f;
                }

               title_bar.getBackground().setAlpha((int)(fraction*255));
            }
        });


        lv_ly = view.findViewById(R.id.lv_layout);
        ring_msg=view.findViewById(R.id.ring_msg_mainhome);
        mBtnAnli =view.findViewById(R.id.btn_anli);
        // FIXME: 18/2/26 listview上方的控件获取焦点可以避免scrollview的滑动
        mBtnAnli.setFocusable(true);
        mBtnAnli.setFocusableInTouchMode(true);
        mBtnAnli.requestFocus();
        mLlBeishu = view.findViewById(R.id.ll_beishu);
        mLvBaodan = view.findViewById(R.id.lv_baodan);
        addBaoDan = view.findViewById(R.id.add_baodan_iv);
        addBaoDan.setOnClickListener(this);
        mBtnAnli.setOnClickListener(this);
        ring_msg.setOnClickListener(this);
        setAdapter();
        initData();
        getBannerData();
    }

    private void setAdapter() {
        setBanner();
        mAdapter = new BaoDanAdapter(getActivity());
        mLvBaodan.setAdapter(mAdapter);
        mAdapter.setDataIsNullListener(new BaoDanAdapter.DataIsNullListener() {
            @Override
            public void DataIsNull(boolean b) {
                if (b) {
                    mLlBeishu.setVisibility(View.VISIBLE);
                    lv_ly.setVisibility(View.GONE);
                } else {
                    mLlBeishu.setVisibility(View.GONE);
                    lv_ly.setVisibility(View.VISIBLE);
                }
            }
        });

        mLvBaodan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle b = new Bundle();
                b.putString("params", mData.get(position).id);
                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bdgl_ckbdxq");
                openActivity(InsuranceActivity.class, b);
            }
        });

    }

    public void initData() {
        isLogin = LoginInfo.getInstance(getActivity()).isLogin();
        if (isLogin) {
            // 登录了
            loadInfo();
        } else {
            // 没登录
            mLlBeishu.setVisibility(View.VISIBLE);
            lv_ly.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ring_msg_mainhome:
                if (loginStatus()) {
                    Bundle bundle =new Bundle();
                    bundle.putInt("from",0);
                    openActivity(MsgActivity.class,bundle);
                }
                break;
            case R.id.btn_anli:
                String url = Constant.root_url + "html/insurance/showexample";
                openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{url});
                break;
            case R.id.add_baodan_iv:
                if (loginStatus()) {
                    final BaoDanDialog dialog = new BaoDanDialog(getActivity()).builder();
                    dialog.setOnButtonClickListener(new MenuBar.OnButtonClickListener() {
                        @Override
                        public void ButtonClick(int position) {
                            switch (position) {
                                case 0:
                                    // 拍照
                                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bdgl_pz");
                                    openActivity(TakePicturesAddActivity.class);
                                    break;
                                case 1:
                                    // 相册
                                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bdgl_xc");
                                    openActivity(AlbumAddActivity.class);
                                    break;
                                case 2:
                                    // 手动
                                    MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_bdgl_sd");
                                    openActivity(ManualAdd1Activity.class);
                                    break;
                            }
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }

                // TODO: 18/1/27 点击按钮

                break;
        }
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
           isLogin = LoginInfo.getInstance(getActivity()).isLogin();
            if (!isLogin) {
                // 没登录
                mLlBeishu.setVisibility(View.VISIBLE);
                lv_ly.setVisibility(View.GONE);
            }
            //开始自动翻页
            homeBanner.startTurning(4000);

        } else {
            //停止翻页
            homeBanner.stopTurning();

        }

    }

    private void loadInfo() {

        if (isLoad) {
            isLoad = false;
            NetUtil netUtil = new NetUtil(getActivity(), JsonApi.INSURANCE_LISTS);
            netUtil.setParams("page", "1");
            netUtil.postRequest("正在加载数据...", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    InsuranceItemBean mBean = new Gson().fromJson(JSONUtil.getData(result),
                            new TypeToken<InsuranceItemBean>() {
                            }.getType());
                    mData = mBean.list;
                    if (mData != null && mData.size() > 0) {
                        mLlBeishu.setVisibility(View.GONE);
                        lv_ly.setVisibility(View.VISIBLE);
                    }
                    mAdapter.setData(mData);
                    isLoad = true;
                }
            });
        }
    }

    private void setBanner() {
        // TODO: 2017/8/28 banner设置
        homeBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerList)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
       //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(this).startTurning(4000);

    }


    @Override
    public void onItemClick(int position) {
        LogUtil.e("轮播图点击-->");
        MobclickAgent.onEvent(App.getContext(),
                "UM_v6_0_0_SY_lbt", bannerList.get(position).title);
        if (bannerList.get(position).type == 1) {
            Uri content_url = Uri.parse(bannerList.get(position).data.gotoUrl);
            if (content_url != null && !content_url.toString().trim().equals("")) {
                Intent intent = new Intent(getActivity(), WebViewPager.class);
                String url = content_url.toString();
                intent.putExtra("startUrl", url);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                }
            }

        } else {
            //跳转到page
            gotoActivity(bannerList.get(position).data.gotoPage.android);
        }
    }

    //轮播跳转具体界面用
    public void gotoActivity(String actname) {

        // TODO: 18/2/24 要改  包名
        String actPrex = "com.bxd.baodan.activity.";
        Class<?> ass = null;
        try {
            ass = Class.forName(actPrex + actname);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (ass != null) {
            Intent intent = new Intent(getActivity(), ass);
            startActivity(intent);
        }
    }
    private void getBannerData() {

        //banner的缓存数据
        String bannerCache = SpUtil.getInstance().getString("new_banner");
        if (bannerCache != null && !bannerCache.isEmpty()) {
            BannerBean bannerBean = new Gson().fromJson(bannerCache, BannerBean.class);
            List<BannerBean.BannerBean_> list = bannerBean.data;
            if (list != null && list.size() > 0) {
                bannerList.clear();
                bannerList.addAll(list);
                homeBanner.notifyDataSetChanged();
            }
        }


        //banner数据
        NetUtil adNet = new NetUtil(this.getActivity(), JsonApi.GET_ADHOME);
        adNet.setParams("app", 2);
        adNet.setParams("channel", Utils.getAppMetaData(App.getContext(), "UMENG_CHANNEL"));
        adNet.setParams("appVer", VersionUtil.getVersionName(this.getActivity()));
        adNet.setParams("position", "wenwen_main_banner");

        adNet.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                BannerBean bannerBean = new Gson().fromJson(result, BannerBean.class);
                List<BannerBean.BannerBean_> list = bannerBean.data;
                if (list != null && list.size() > 0) {
                    SpUtil.getInstance().savaString("new_banner", result);

                    bannerList.clear();
                    bannerList.addAll(list);
                    homeBanner.notifyDataSetChanged();
                }

            }
        });
    }
}
